package com.mornd.gulimall.cart.web.v1;

import com.mornd.gulimall.cart.entity.Cart;
import com.mornd.gulimall.cart.entity.CartItem;
import com.mornd.gulimall.cart.service.ICartService;
import com.mornd.gulimall.common.core.constant.ServerUrls;
import com.mornd.gulimall.common.core.result.AjaxResult;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Min;
import java.util.List;

/**
 * @author: mornd
 * @dateTime: 2023/8/20 - 7:56
 */

@Validated
@Controller
public class CartController {
    @Resource
    private ICartService cartService;

    @GetMapping({"/", "cart.html", "cart"})
    public String cartPage(Model model, HttpSession session) {
        Cart cart = cartService.getCart();
        model.addAttribute("cart", cart);
        return "cartList";
    }

    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId,
                            @RequestParam("num") @Min(1) Integer num,
                            RedirectAttributes redirectAttributes) {
        cartService.addToCart(skuId, num);
        redirectAttributes.addAttribute("skuId", skuId);
        return "redirect:" + ServerUrls.CART + "/addToCartSuccess";
    }

    @GetMapping("/addToCartSuccess")
    public String addToCartSuccess(@RequestParam Long skuId, Model model) {
        CartItem item = cartService.getCartItem(skuId);
        model.addAttribute("item", item);
        return "success";
    }

    @GetMapping("/deleteItem/{skuId}")
    public String deleteItem(@PathVariable("skuId") Long skuId) {
        cartService.deleteItem(skuId);
        return "redirect:" + ServerUrls.CART + "/cart";
    }

    @ResponseBody
    @GetMapping("/cart/getCartItems/{userId}")
    public AjaxResult getCartItems(@PathVariable Long userId) {
        List<CartItem> items = cartService.getCartItems(userId);
        return AjaxResult.success(items);
    }
}
